<template>
	<view class="content">
		<popup :open="openPopup2" :position="position" :percent="percent" :background="background" @close="openPopup2 = false" v-show="isShow">
		  <view class="set-type" style="text-align: center;">
			<button class="st" @click="setPay('现金')" :style="'background:'+pbackground1+';color:'+pcolor1" :disabled="isDisabled">现金</button>
			<button class="st" @click="setPay('支付宝')" :style="'background:'+pbackground2+';color:'+pcolor2" :disabled="isDisabled">支付宝</button>
			<button class="st" @click="setPay('微信')" :style="'background:'+pbackground3+';color:'+pcolor3" :disabled="isDisabled">微信</button>
		  </view>
		</popup>
		<popup :open="openPopup" :position="position" :percent="percent" :background="background" @close="openPopup = false">
		  <view class="set-type" style="text-align: center;">
			<button class="st md" @click="setType(1)" :style="'background:'+background1+';color:'+color1">门店销售</button>
			<view class="sel-member" v-show='show_member'>
				<view style=" float:left;width: 25%;
				font-size: 16px;
				line-height: 50px;">选择会员: </view>

				<input type="text" id="getVal" class="input-search" placeholder="请输入搜索内容" v-model="searchWord" v-on:input ="inputChange" @focus="inputFocus" />
				<view v-show="show_result" class="show_result">
					<view class="b-line" v-for="(fmember, findex) in smember_data"  @click="sel_member(fmember.muCode,fmember.muNickName,fmember.alId,fmember.muId,fmember.waMoney)">
						{{fmember.muMobile}} - {{fmember.muNickName}}
					</view>
					<div class="search-results" v-show="resultNull">无相关会员信息</div>
				</view>
				<view v-show="hmember" class="hmember">已选择会员：{{current_member_info}}</view>
			</view>
			<button class="st " @click="setType(2)" :style="'background:'+background2+';color:'+color2" >内销申请</button>
			<button class="st" disabled="disabled">代理提货</button>
			<!-- <button class="qr" @click="sett()" v-show="utype!='1'">确认</button> -->
		  </view>
		</popup>
		<view class="top-details" :style="'justify-content:'+displayType">
			<div class="sales-type">
				<img src="../../static/sale-type.png" alt="销售类型">
				<span class="carType">{{carType}}</span>
			</div>
			<div class="member-account" v-show="utype=='1'">
				<img src="../../static/member-account.png" alt="用户信息">
				<span class="account-Type">{{current_member_info}}~{{alName}}</span>
			</div>
			<div class="switch-account" style="margin-right: 6px;" v-show="utype=='1'" @click="delAll">
				<img src="../../static/switch-user.png" alt="切换">
				<span class="switch-user">切换会员</span>
			</div>
			<div class="switch-account" v-show="utype!='1'" @click="delAll">
				<img src="../../static/switch-user.png" alt="切换">
				<span class="switch-user">切换出货</span>
			</div>
			
			
		</view>
		<scroll-view class="menu-wrapper" scroll-y :style="'height:'+height+'px'">
			<view ref="menuWrapper">
				<!--  :class="{'current': currentIndex == index}" @click="selectMenu(index,$event)" -->
				<view style="position: relative;" v-for="(item,index) in goods" :key="index" ref="menuList" @click="select(index)"
				 :class="{'current': currentIndex == index}">

					<view class="menu-item">{{item.name}}</view>
					<text class="allcount" v-if="getAllCount>=item.count&&item.count>0">{{item.count}}</text>
					<!-- <text class="allcount">1</text> -->
				</view>
			</view>
		</scroll-view>
		<!--  @scroll="scroll" -->

		<view class="foods-wrapper" :style="'height:'+height+'px'">
			<view ref="foodsWrapper">
				<scroll-view ref="foodList" scroll-y :style="'height:'+height+'px'" :scroll-top="foodSTop" :class="{ 'foods':1,'active': currentIndex == i}" v-for="(item, i) in goods" :key="i" :id="item.goodsId">

					<!-- <view class="food-title" style="background: #f3f5f7">
						{{item.name}}
					</view> -->
					<view class="food" v-for="(food, index) in item.foods" :key="index">
						<image :src="food.img" mode="" style="width: 75px;height: 75px;"></image>
						<view class="food-info">
							<text style="font-size: 15px;margin-top: 2px;">{{food.name}}</text>
							<!-- <text style="font-size: 13px;margin: 2px 0;">{{food.description}}</text> -->
							<text style="font-size: 13px;margin: 2px 0 4px;">库存{{food.sellCount}}</text>

							<!-- 加减 -->
							<view class="food-btm">
								<text class="food-price" v-show="utype=='1'">
									<text class="was"><span>￥{{food.price}}</span></text>
									￥{{food.memberPrice}}
								</text>
								<cartcontrol :food="food" @add="addCart" @dec="decreaseCart" v-show="food.sellCount>0"></cartcontrol>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>

		</view>
		<shopcart :goods="goods" :utype="utype" @toggleListCart="toggleListCart" :isShowList="isShowList" :accountMoney="accountMoney" @add="addCart" :clearStatus="clearStatus" @updPrice="updPrice" @dec="decreaseCart" @delAll="delAll"  v-on:shopcartBuy="shopcartBuy"></shopcart>
		<div id="loader-screen"></div>

	</view>
</template>

<script>
	import shopcart from '@/components/shopcart.vue';
	import cartcontrol from '@/components/cartcontrol.vue'
	import popup from '@/components/YYT-popup/YYT-popup.vue';
	import mSearch from "@/components/mehaotian-search/mehaotian-search.vue"
	import Vue from 'vue';
	import axios from 'axios';
	// import BScroll from 'better-scroll'
	const scKey = 1;
	export default {
		data() {
			return {
				isShowList:false,
				isShow:true,
				show_member:false,
				current_member_id:"",
				current_member_info:"",
				hmember:false,
				member_min_price:[],
				shoper_min_price:[],
				background2:"#f8f8f8",
				background1:"#f8f8f8",
				color1:"#000",
				color2:"#000",
				displayType:"center",
				pbackground2:"#f8f8f8",
				pbackground1:"#f8f8f8",
				pbackground3:"#f8f8f8",
				pcolor1:"#000",
				pcolor2:"#000",
				pcolor3:"#000",
				show_result:false,
				smember_data:[],
				title: 'Hello',
				goods: [],
				utype:0,
				utype_name:"",
				openPopup: false,
				openPopup2: false,
				position: 'top',
				background: '#fff',
				openAdPopup: false,
				percent: 0,
				showText: false,
				change: false,
				loopTimer: false,
				sizeSort: 'asc',
				height: 0,
				foodSTop: 0,
				currentIndex: 0,
				carType:"门店销售",
				isDisabled: false,
				alName:'',
				searchWord:'',
				timer:null,
				resultNull:false,
				toView: '',
				accountMoney:0,
				clearStatus:false
			}

		},
		components: {
			shopcart,
			cartcontrol,
			popup,
			mSearch
		},
		onLoad() {
			//选择类型
			if(this.utype=="" ){
				this.open('center');
			}
			this.height = Number(uni.getSystemInfoSync().windowHeight) - 105;
			this.getGoodslist();
		},
		 onShow(){
		 	//选择类型
			this.utype="";
			this.background2="#f8f8f8";
			this.background1="#f8f8f8";
			this.color1="#000";
			this.color2="#000";
			this.carType="门店销售";
			this.displayType="center";
			this.show_member=false;
			
		 	if(this.utype=="" ){
		 		this.open('center');
		 	}
		 	this.height = Number(uni.getSystemInfoSync().windowHeight) - 105;
			this.delAll();
		 	this.getGoodslist();
		 },
		computed: {
			
			getList() {
				let result = [];
				this.goods.forEach((good) => {

					good.foods.forEach((food) => {

						if (food.count) {
							result.push(food)
							
						}
					})
				})
				// console.log('result', result);
				return result

			},
			
			// 获得购物车所有商品数量
			getAllCount: function(item) {
				// console.log('item', item)
				let result = [];
				let count = 0;
				var goodsJson = JSON.parse(JSON.stringify(this.goods));
				// console.log(goodsJson)
				for (let i = 0; i < goodsJson.length; i++) {
					count = 0;
					// console.log('goodsJson[i]:')
					// console.log(goodsJson[i])
					goodsJson[i].foods.forEach((food) => {
						
						// console.log('food',food);
						if (food.count >= 0) {
							count += food.count
							Vue.set(this.goods[i], 'count', count)
						}
					})
					// console.log('result', count);
					result.push(count)
				}

				result.sort(function(a, b) {
					return a - b;
				})
				count = result[result.length - 1]
				// console.log('result', count);
				return count;
				}
			},
			watch: {
	            searchWord () {
	                if(this.timer){
	                    clearTimeout(this.timer)
	                }
	                if(!this.searchWord){
	                    this.smember_data=[]
	                    //return list
	                }
	                this.timer=setTimeout(()=> {
	                    const result=[]
						this.search(this.searchWord);     
	                    //this.list=result
	                    //console.log(result)
	                },500)
	            }
			},
			methods:{
				toggleListCart() {
					
					if (this.getList.length) {
						this.isShowList = !this.isShowList;
					}
				},
				getMemberPrice(member_id){
						return axios(uni.getStorageSync('api_url2')+'/main/getGoodsPrice?sId='+uni.getStorageSync('shop_id')+'&muCode='+member_id);
				},
				getAgencyLevelName(alid,muid){
					uni.request({
						url: uni.getStorageSync('api_url')+'/agencyLevel/get/'+alid+'?acKey='+muid,
						complete: (result) => {
							uni.hideLoading();
							if(result.data.code != 1){
								uni.showToast({
									title:result.data.msg
								});
							}else{
								//console.log(result.data.data.alName);
									this.alName = result.data.data.alName
							}
							
						},
					});
				},
				getGoodslist(){
					uni.request({
						url: uni.getStorageSync('api_url')+'/storeGoods/getList?scKey='+uni.getStorageSync('shop_id')+'&page=1&perPage=200',
						complete: (result) => {
							 //console.log(result)
							if(result.data.code != 1){
								uni.showToast({
									title:result.data.msg
								});
							}else{
								let data = result.data.data.data;
								// console.log(data)
								let listSingle = [];
								let listCard = [];
								let listCombo = [];
								for(let i=0;i<data.length;i++){
									let tmp = {};
									tmp.id = data[i].sgId;
									tmp.name = data[i].sgName;
									tmp.price = data[i].sgPrice;
									tmp.oldPrice = data[i].sgPrice;
									tmp.description = data[i].sgDesc;
									tmp.sellCount = data[i].sgNum;
									tmp.img = data[i].sgLogo;
									tmp.sgIsTimeCard = data[i].sgIsTimeCard;
									if (data[i].sgChildNum <= 1 && data[i].sgIsTimeCard == 0){
										listSingle.push(tmp);
									}
									if (data[i].sgIsTimeCard == 1){
										listCard.push(tmp);
									}
									if (data[i].sgChildNum > 1 && data[i].sgIsTimeCard == 0){
										listCombo.push(tmp);
									}
								}

								let goods = [];
								let tmp1 = {};
								tmp1.name = "单品";
								tmp1.foods = listSingle;
								goods.push(tmp1);
								if (this.show_member == true){
									let tmp2 = {};
									tmp2.name = "卡项";
									tmp2.foods = listCard;
									goods.push(tmp2);
								}
								// let tmp3 = {};
								// tmp3.name = "套装";
								// tmp3.foods = listCombo;
								// goods.push(tmp3);
								this.goods = goods;
							}
						}
					});
				},
				inputChange() {
					
				},
				inputFocus(){
					
				},
				search(val) {
					//console.log(val);
						if(val!=""){
							uni.showLoading({
								title: '获取信息中'
							});
							uni.request({
								url: uni.getStorageSync('api_url')+'/member/getList?mcKey='+uni.getStorageSync('shop_id')+'&keyword='+val,
								complete: (result) => {
									uni.hideLoading();

									if(result.data.data.count == 0){
										this.resultNull=true;
									}
									else{
										this.resultNull=false;
									}
									if(result.data.code != 1){
										uni.showToast({
											title:result.data.msg
										});
									}else{
										this.smember_data=result.data.data.data;
										this.show_result=true;
									}
								},
								});
						}
				},
				open: function(position) {
					
				this.position = position;
				this.openPopup = true;
			},
			 sel_member:async function(mid,name,alId,muId,moeny){
				this.current_member_id=mid;
				this.getAgencyLevelName(alId,muId);
				this.accountMoney = moeny;
				this.hmember=true;
				this.current_member_info=name;
				this.show_result=false;
				this.openPopup = false;
				let price = await this.getMemberPrice(this.current_member_id);
				this.member_min_price = price.data.data;
				//console.log(this.member_min_price);
				//setTimeout(()=>{
				this.goods.forEach((good) => {
					good.foods.forEach((food) => {
							var memberPrice=0;
							var minPrice=0;
							//console.log(this.member_min_price);
							this.member_min_price.forEach((mp) => {
								if(mp.goodsId==food.id){
									memberPrice = mp.goodsPrice;
									minPrice = mp.goodsMinPrice;
								}
							});
							Vue.set(food, 'memberPrice', memberPrice > 0 ? memberPrice : food.price);
							Vue.set(food, 'minPrice', minPrice);
							
					})
				})
				//},1000);
			},
			//出货类型
			setType:function(val){
				this.utype=val;
				if(this.utype==1){
					this.utype_name="门店销售";
					this.show_member=true;
					this.getGoodslist();
					this.background1='#6d1c79';
					this.background2='#f8f8f8';
					this.color1='#fff';
					this.color2='#000';
					this.carType="门店销售";
					this.displayType="space-between";
					this.foodSTop=0;
				}else{
					this.utype_name="内销申请";
					this.background2='#6d1c79';
					this.background1='#f8f8f8';
					this.color1='#000';
					this.color2='#fff';
					this.show_member=false;
					this.openPopup = false;
					this.isShow=false;
					this.getGoodslist();
					this.carType="内销申请";
					this.displayType="space-around";
					var newGoods = [];
					newGoods.push(this.goods[0]);
					// newGoods.push(this.goods[2]);
					this.goods = newGoods;
					this.currentIndex=0;
					this.foodSTop=0;
				}
			},
			//qr
			sett:function(){
			if(this.utype>0){	
					if(this.utype==1){
						if(this.current_member_id==""){
							uni.showToast({
								title:'请选择会员',
								icon:'none'
							});
							
						}else{
							this.openPopup = false;
						}
					}else{
						this.openPopup = false;
						this.isShow=false;
						this.getGoodslist();
					}
					
				}else{
					uni.showToast({
						title:'请选择出货方式',
						icon:'none'
					});
				}
			},
			// 点击侧边栏
			select(index) {
				this.currentIndex = index;
			},	
			updatePrice: function(item) {
				// console.log('ev', JSON.stringify(item))
					this.goods.forEach((good) => {
						good.foods.forEach((food) => {
							if (item.id == food.id)
								food.price = item.price;
						})
					})
			},
			updPrice:function(item) {
				//console.log(item);
					this.goods.forEach((good) => {
						good.foods.forEach((food) => {
							if (item.id == food.id){
								Vue.set(food, 'memberPrice',item.memberPrice)
							}
						})
					})
				
			},
			addCart: function(item) {
				if (item.count >= 0) {
					item.count++
					if(item.count>=item.sellCount){
						item.count=item.sellCount;
					}
					this.goods.forEach((good) => {
						good.foods.forEach((food) => {
							if (item.id == food.id)
								food.count = item.count
						})
					})
					
				} else {

					this.goods.forEach((good) => {
						good.foods.forEach((food) => {
							if (item.id == food.id){
								Vue.set(food, 'count', 1)
								var minPrice=0;
								this.member_min_price.forEach((mp) => {
									if(mp.goodsId==item.id){
										minPrice=mp.goodsMinPrice;
									}
								});
								Vue.set(food, 'show_edit_price', 0);
								Vue.set(food, 'minPrice', minPrice>0 ? minPrice:food.price);
							}
						})
					})
				}

			},
			decreaseCart(item) {
				if (item.count) {
					item.count--
					this.goods.forEach((good) => {
						good.foods.forEach((food) => {
							if (item.id == food.id)
								food.count = item.count
							
						})
					})
				}
			},
			// 清空购物车
			delAll() {
				this.goods.forEach((good) => {
					good.foods.forEach((food) => {
						if (food.count) {
							food.count = 0
							
						}
					})
				})
				this.current_member_id="";
				this.current_member_info="";
				this.alName="";
				this.openPopup = true;
				this.isShow=true;
				this.hmember=false;
				this.show_result =false;
				this.searchWord = '';
				this.isShowList=false;
				this.clearStatus=true;
			},
			shopcartBuy: function (shopcartBuy) {
				//console.log(shopcartBuy);
				this.payCommit(shopcartBuy[0],shopcartBuy[1],shopcartBuy[2],shopcartBuy[3]);
			},
			setPay(type){
				this.payCommit(type);
			},
			payCommit(type,remark,accountPay,cardPay){
				
				var ids="",nums="",prices="",remarks="";
				this.goods.forEach((good) => {
					good.foods.forEach((food) => {
						if(food.count!="" && food.count!=undefined){
							ids+=(ids!="" ? "|" :"")+food.id;
							nums+=(nums!="" ? "|" :"")+food.count;
							prices+=(prices!="" ? "|" :"")+food.memberPrice*food.count;
							remarks+=(remarks!="" ? "|" :"")+remark;
						}
						
					})
				});
				if(ids == ""){
					uni.showToast({
						title:'没有选择出货的商品',
						icon:'none'
					});
					this.openPopup2 = false;
					this.isDisabled = false;
					return false;
				}

				var reqUrl = uni.getStorageSync('api_url2')+'/main/sellGoods';
				if (!this.show_member){
					reqUrl = uni.getStorageSync('api_url2')+'/main/sellGoodsInside'
				}
				$('#appLoader').show();
				$('#loader-screen').show();
				uni.request({
					url: reqUrl,
					method: 'POST',
					data: {sId:uni.getStorageSync("shop_id"),
					auCode:uni.getStorageSync("admin_code"),
					muCode:this.current_member_id,
					sgId:ids,
					sgoMemo:remarks,
					sgoSaleNum:nums,
					sgoSalePrice:prices,
					createUser:uni.getStorageSync("admin_name"),
					sgoPayWay:type,
					isCustomPrice:0,
					accountPay:accountPay,
					cardPay:cardPay,
					},
					header:{'content-type': 'application/x-www-form-urlencoded'},
					complete: (result) => {
						$('#appLoader').hide();
						$('#loader-screen').hide();
						uni.hideLoading();
						this.openPopup2=false;
						this.isDisabled =false;
						if(result.data.code != 1){
							uni.showToast({
								title:result.data.msg,
								icon:'none'
							});
						}else{
							uni.showToast({
								title:"出货成功",
							});
							const _this=this;
							
							setTimeout(function(){
								_this.delAll();
							},2100);
							
							
						}
						this.getGoodslist();
					},
				});
			}
		}
	}
</script>

<style>
	.content {
		/* text-align: center; */
		/* height: 400upx; */
		display: flex;
		position: absolute;
		top: 0;
		bottom: 55px;
		width: 100%;
		overflow: hidden;
	}

	.current {
		position: relative;
		z-index: 0;
		background-color: #fff;
		color: #6d1c79;
		border-left: 3px solid #6d1c79;
	}

	.menu-wrapper {
		text-align: center;
		width: 22%;
		display: flex;
		flex-direction: column;
		background: #dcdcdc;
		margin-top: 50px;
	}

	.menu-item {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 50px;
		font-size: 16px;
		color: #6d1c79;
		
	}

	.allcount {
		position: absolute;
		right: 6px;
		top: 8px;
		display: inline-block;
		padding: 0 4px;
		font-size: 9px;
		line-height: 16px;
		font-weight: 400;
		border-radius: 50%;
		background-color: #f01414;
		color: #ffffff;
	}

	.foods-wrapper {
		width: 78%;
	}
	.foods-wrapper .foods{
		margin-top: 50px;
		display: none;
	}
	.foods-wrapper .foods.active{
		margin-top: 50px;
		display: block;
	}

	.food{
		margin-bottom: 10px;
		padding: 15px 10px;
		box-shadow: 0px 0px 5px #888888;
	}
	.food,
	.food-btm,
	.content {
		display: flex;
		flex-direction: row;
	}

	.food-title {
		padding: 2px 0;
	}

	.food-info {
		margin-left: 10px;
		margin-right: 16px;
		display: flex;
		flex-direction: column;
		flex: 2;
		justify-content: center;
	}

	.food-btm {
		justify-content: space-between;

	}

	.food-price {
		color: #f01414;
		font-size: 14px;
		letter-spacing: -0.5px;
	}
	.set-type button{margin-top:15px;clear: both;}
	.show_result{ background: #efefef;    max-height: 123px;
    overflow-y: auto;
    clear: both;}
 
	.show_result .b-line{
		line-height: 40px;
		font-size: 18px;
    border-top: 1px solid #fff;}
	.hmember{width: 100%;
    color: #f00;
    display: inline-block;}
	
	.top-details{
		position: fixed;
		    width: 100%;
		    background: #fff;
		    font-size: 14px;
		    height: 50px;
		    -webkit-box-shadow: 0px 0px 5px #888888;
		    box-shadow: 0px 0px 5px #888888;
		    z-index: 89;
			line-height: 50px;
			display: flex;
			justify-content: space-between;
			overflow: hidden;
	}
	.top-details .sales-type,
	.top-details .member-account,
	.top-details .switch-account{
		position: relative;
		display: inline-block;
	}
	.top-details .carType,
	.top-details .account-Type,
	.top-details .switch-user{
		padding-left: 25px;
	}
	.top-details .sales-type img,
	.top-details .member-account img,
	.top-details .switch-account img{
		    width: 20px;
		    height: 20px;
		    position: absolute;
		    top: 50%;
		    margin-top: -10px;
		    left: 5px;
	}
	.sel-member .input-search {
		width: 75%;
		line-height: 50px;
		float: right;
		height: 50px;
		font-size: 16px;
	}
	.food-price .was{
	    font-size: 13px;
	    text-decoration: line-through;
	    color: #aaa;
	    font-weight: normal;	
	}
	.search-results{
		text-align: center;
		color: red;
		font-size: 16px;
		margin: 20px auto;
	}

	@media all and (max-width: 374px) {
	    .top-details {
	            font-size: 12px;
	    }
	}
	#loader-screen {
		display: none;
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, .6);
		-webkit-transition: opacity .3s;
		-o-transition: opacity .3s;
		transition: opacity .3s;
		z-index: 10000;
	}
</style>
